import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getAppByTenantIdAndUserIdAndCode, getAppServiceUrl } from '@/api/security'
import storage from '@/utils/storage'
import { message, isIE } from '@/utils/util'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
router.beforeEach((to, from, next) => {
  store.dispatch('setRouter', to)
  NProgress.start() // start progress bar
  if (to.path === '/login') {
    next({ path: '/' })
    NProgress.done()
  } else {
    if (store.getters.loggedInUser === '') {
      let serviceApi = locale.serviceApi
      let localAppCode = store.getters.code
      let appCode = ''
      for (let key in serviceApi) {
        appCode += key + ','
      }
      // store.dispatch('loadLanguageData')// 加载国际化文件
      setTimeout(() => {
        let response = {'code': 'SECURITY-0000', 'msg': '', 'data': {'PLATFORM': 'http://192.168.0.202/platform', 'FMB': ''}, 'success': true}
        if (response.success && response.data !== null) {
          let serviceUrl = response.data
          locale.platform = serviceUrl.PLATFORM // 平台跳转地址必须

          for (let key in serviceApi) {
            if (serviceApi.hasOwnProperty(key)) {
              if (serviceApi[key] !== undefined && serviceApi[key] === '') {
                serviceApi[key] = serviceUrl[key]
              }
            }
          }
          store.dispatch('getLoggedInUser').then(res => { // 拉取用户信息
            let userobj = res.data
            store.dispatch('setLanguage', userobj.locale)
            store.dispatch('GenerateMenus', []).then(() => {
              if (isIE()) {
                document.body.innerHTML = '<h1>It is only available for the Edge web browser</h1>'
                next()
              } else {
                if (to.redirectedFrom !== undefined) {
                  next({ path: to.redirectedFrom })
                } else {
                  next({ ...to, replace: true })
                }
              }
            })
          }).catch(() => {
            store.dispatch('LogOut').then(() => {
              window.location.href = locale.platform + '?code=' + localAppCode
            }).catch(() => {
              window.location.href = locale.platform + '?code=' + localAppCode
            })
          })
        }
      }, 100)
    } else {
      if (storage.getSession('routePath')) {
        let routePath = storage.getSession('routePath')
        let lastUrl = getLastUrl(window.location.href, '/')

        if (routePath === lastUrl) { // 动态路由页面的刷新事件
          storage.removeSession('routePath')
          router.replace(routePath) // replace,保证浏览器回退的时候能直接返回到上个页面，不会叠加
        }
      }
      next()
    }
  }
})

router.afterEach((to, from) => {
  storage.setSession('routePath', to.path)
  NProgress.done() // finish progress bar
})

let getLastUrl = (str, yourStr) => str.slice(str.lastIndexOf(yourStr))
